// $codepro.audit.disable
package org.mysofts.eclipseman.archives; // $codepro.audit.disable tooManyViolations

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Collection;

import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.apache.commons.io.FileUtils;
import org.mysofts.eclipseman.util.AppLog;
import org.mysofts.eclipseman.util.MessageProvider;

/**
 * Abstract Tarred Gzip Archive.
 * 
 * @author reda
 * 
 */
abstract class AbstractTarredGzipArchive extends Archive { // $codepro.audit.disable
															// declareDefaultConstructors
	// [start] constructors
	/**
	 * Constructeur.
	 * 
	 * @param pExtension
	 *            extension.
	 * @param pArchive
	 *            Fichier archive.
	 */
	public AbstractTarredGzipArchive(final String pExtension,
			final File pArchive) {
		super(pExtension, pArchive);
	}

	// [end]

	// [start] AbstractArchive Implémentation
	@Override
	public final void archive(final File fileToArchive) throws IOException {
		throw new UnsupportedOperationException(MessageProvider.get("logs")
				.sub("archives").sub("tgz").sub("archive").sub("unsupported")
				.value());
	}

	@Override
	public final Collection<File> extract(final File extractTo)
			throws IOException {
		TarArchive tar = getEnclosingTar();
		return tar.extract(extractTo);
	}

	@Override
	public final Collection<String> listFiles() throws IOException {
		TarArchive tar = getEnclosingTar();
		return tar.listFiles();
	}

	// [end]

	/**
	 * Décompresse le fichier GZIP vers un fichier temporaire (ce fichier va
	 * être supprimé automatiquement à la fin de la JVM.
	 * 
	 * @return Instance de {@link TarArchive} qui gère le fichier temporaire.
	 * @throws IOException
	 *             Si l'extraction qui a causé problème.
	 */
	private TarArchive getEnclosingTar() throws IOException {
		AppLog.debug(MessageFormat.format(
				MessageProvider.get("logs").sub("archives").sub("tgz")
						.sub("open").sub("start").value(), this
						.getArchiveFile().getAbsolutePath()));
		try {
			File tempFile = File.createTempFile("temp-", ".tar"); //$NON-NLS-2$

			FileInputStream in = new FileInputStream(this.getArchiveFile());
			GzipCompressorInputStream gzipin = new GzipCompressorInputStream(in);
			try {
				FileUtils.copyInputStreamToFile(gzipin, tempFile);
			} finally {
				in.close();
				gzipin.close();
			}
			FileUtils.forceDeleteOnExit(tempFile);
			AppLog.debug(MessageFormat.format(
					MessageProvider.get("logs").sub("archives").sub("tgz")
							.sub("open").sub("end").value(), this
							.getArchiveFile().getAbsolutePath(), tempFile
							.getAbsolutePath()));
			return new TarArchive(tempFile);
		} catch (IOException ex) {
			AppLog.error(MessageFormat.format(
					MessageProvider.get("logs").sub("archives").sub("tgz")
							.sub("open").sub("error").value(), this
							.getArchiveFile().getAbsolutePath()), ex);
			throw ex;
		}
	}

}